package com.abc.robot01.vivemodel

import android.util.Log
import androidx.compose.runtime.mutableStateOf
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.abc.robot01.retrofit.RetrofitService
import com.abc.robot01.retrofit.bean.DataItem
import com.abc.robot01.retrofit.bean.LocalConfig
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch

class HomePageViewModel : BaseViewModel() {
    val TAG="HomePageViewmodel"

    // 使用 StateFlow 来管理网络请求结果
    private val _posts = MutableStateFlow<List<DataItem>>(emptyList())
    val configs: StateFlow<List<DataItem>> = _posts

    val list= mutableListOf<LocalConfig>()

//    var currentPage:Int= 0

    val fullScreen = mutableStateOf(false)

    // 在 ViewModel 初始化时获取数据
    init {
        fetchData()
    }

    private fun fetchData() {
        Log.e(TAG, "fetchData:$Robot")
        viewModelScope.launch {
            try {
                 _posts.value = RetrofitService.instance.getHomePage(
                     Robot.accessToken,
                     Robot.robotId,
                     Robot.companyId).data.also {
                   it.forEach{
                       it.configs.forEach {
                           Log.e(TAG, "首页配置 Item:${it}")
                       }
                     }
                 }
            } catch (e: Exception) {
                Log.e(TAG,""+e.message)
                e.printStackTrace()
            }
        }
    }
}

